﻿using System.Linq;
using SharePoint.Security.ConfigAnalyzer.Engine.Base;
using SharePoint.Security.ConfigAnalyzer.Engine.Common;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.SecureStoreService.Server;
using System.Reflection;

namespace SharePoint.Security.ConfigAnalyzer.Engine.Rules.Diagnostic
{
    class SecureStoreAuditLog: BaseRule
    {
        public SecureStoreAuditLog()
        {
            RuleInfo = new RuleInfo
                           {
                               Title = "Secure Store Service Audit Log",
                               Description = "Secure Store Service Audit Log should be turned on (Central Admin > Manage Service Application > ServiceApplication.aspx)",
                               ExpectedValue = "True"
                           };
        }

        #region Overrides of BaseRule

        public override void Validate()
        {
            SPFarm spFarm = ObjectHelper.Farm;
            SPService spService = spFarm.Services.Where(s => s.TypeName == "Secure Store Service").First();

            SPServiceApplication spApp = spService.Applications.ToList().SingleOrDefault(a => a.TypeName.Equals("Secure Store Service Application"));   
             
            if (spApp is SecureStoreServiceApplication)
            {
                SecureStoreServiceApplication secureApp = spApp as SecureStoreServiceApplication;                

                //Using reflection to read 'internal' marked 'AuditEnabled' property
                PropertyInfo pInfo = secureApp.GetType().GetProperty("AuditEnabled", 
                                    System.Reflection.BindingFlags.Public | 
                                    System.Reflection.BindingFlags.NonPublic | 
                                    System.Reflection.BindingFlags.Instance);

                bool auditEnabled = (bool)pInfo.GetValue(secureApp, null);

                if (auditEnabled)
                {
                    Status = Status.Pass;
                    CurrentValue = auditEnabled.ToString();
                }
                else
                {
                    Status = Status.Fail;
                    CurrentValue = auditEnabled.ToString();
                }                                  
            }
        }

        #endregion
    }
}
